
import xlwt, xlrd
from xlutils.copy import copy

# dict1 = {'数学': 95, '语文': 89, '英语': 90,'地理':100}
# for i in dict1.keys():
#     print(i)
# #遍历字段的键
# for i in dict1.values():
#     print(i)
# #遍历字段的值
# for k,v in dict1.items():
#     print(k,v)

# https://blog.csdn.net/weixin_42321517/article/details/112390194 全解析！9个处理Excel的Python库，到底哪个最好用？
# https://www.jb51.net/article/205141.htm python中xlrd模块的使用详解
# https://www.cnblogs.com/Johnny-z6951/p/15628132.html 使用Pyinstall将PyQT5打包成.exe应用程序（包含图标一同打包）
# pyinstaller -w -F -i 1-1.ico daochu_system.py
# pyinstaller -F -i 1-1.ico daochu_system.py
# https://blog.csdn.net/weixin_38037405/article/details/123705853 这可能是全网最完整的 Python 操作 Excel 库总结
# https://blog.csdn.net/qq_55957975/article/details/117687894  PyQt5安装及Pycharm配置详细教程（win10)
# https://blog.csdn.net/qq_44597856/article/details/125664137 Python Qt GUI设计：QLineEdit和QTextEdit文本框类（基础篇—13）

# filename = '1.xls'
# infos = []
# imgspath = r"C:\Users\SV00290116\Desktop\394存在145"
# imgspathList = os.listdir(imgspath)
# for name_daochu in imgspathList:
#     im = cv2.imdecode(np.fromfile(os.path.join(imgspath,name_daochu), dtype=np.uint8), -1)
#     if im is None:
#         logger.info(os.path.join(name_daochu))
#         continue
#     code = {}
#     imageName = name_daochu.split('\\')[-1]
#     codeNanme = imageName.split('_')[0]
#     code[codeNanme] = "Found"
#     infos.append(code)
#
# if os.path.exists(filename):
#     # 存在执行追加方法
#     ExcelUtils.append_to_excel(infos, filename)
# else:
#     # 不存在执行创建和写入
#     ExcelUtils.write_to_excel(infos, filename)
# infos.clear()

name1 = 0
class ExcelUtils:
    """写入Excel文件"""
    name2 = name1
    @staticmethod
    def write_to_excel(infos, filename, sub = None,sheetname='sheet1'):
        """重写excel"""
        # 1、创建工作簿
        work_book = xlwt.Workbook(encoding='utf-8')
        # 2、创建表单
        sheet = work_book.add_sheet(sheetname)
        # 3、写表头，由于keys方法得到的是迭代器，不能直接使用len方法，需要转为列表。表头写在第一行，使用字典的键最为每一列属性名。
        rows = 0
        for dict_code in infos:
            if sub != None:
                sub.put(dict_code)
            if isinstance(dict_code, dict):
                for key, value in dict_code.items():
                    sheet.write(rows, 0, key)
                    sheet.write(rows, 1, value)
            else:
                sheet.write(rows, 0, dict_code)
            rows += 1
        work_book.save(filename)
        print("写入成功！")



    @staticmethod
    def append_to_excel(infos, filename, sheetname='sheet1'):
        """追加写入Excel文件"""
        # 1、打开已有工作簿
        work_book = xlrd.open_workbook(filename=filename)
        # 2、获取所有表单的名称，这里获取第一个表单名
        sheetname = work_book.sheet_names()[0]
        # 3、通过名字来获取sheet表单
        sheet = work_book.sheet_by_name(sheetname)
        # 4、获取已有行数
        old_rows = sheet.nrows
        # 将xlrd的workbook变成xlwt的workbook，这里使用了xlutils插件中的copy方法。
        new_work_book = copy(work_book)
        # 获得表单
        new_sheet = new_work_book.get_sheet(0)
        new_rows = old_rows
        for dict_code in infos:
            for key, value in dict_code.items():
                new_sheet.write(new_rows, 0, key)
                new_sheet.write(new_rows, 1, value)
            new_rows += 1
        new_work_book.save(filename)
        print("追加成功！")
